#-*- encoding : utf-8 -*-

require 'spidr'
require 'fileutils'
require 'util'
require 'remember'

module Album

  # 访问网页的间隔，间隔太小会暂时被ban
  TIME_INTERVAL = 1
  # 相册略缩图页面图片选择器
  PIC_SELECTOR = 'div.photo_wrap>a:first-child'
  # 分享节点选择器，获取其中data-title属性作为相册介绍
  SHARE_SELETOR = 'span.rec>a.bn-sharing'
  # 相册图片总数和创建时间的选择器
  QUANTITY_TIME_SELECTOR = 'div.wr>span.pl' 
  # 相册作者和标题的选择器
  AUTHOR_TITLE_SELECTOR = 'title'
  # 判断页面是否包含“查看大图”的选择器
  SINGLE_LARGE_PIC_JUDGE_SELECTOR = 'div.report_link a'
  # 大图页面选择器
  SINGLE_LARGE_PIC_SELECTOR = 'td#pic-viewer>a>img'
  # 单个图片所在div的选择器
  SINGLE_PIC_DIV_SELECTOR = 'div#link-report'
  # 单个图片的选择器，以图片div为父节点
  SINGLE_PIC_SELECTOR = 'div>a.mainphoto>img'
  # 单个图片的描述选择器，以图片div为父节点
  SINGLE_PIC_DESC_SELECTOR = 'div.photo_descri>div.edtext.pl'
  # “下一页”选择器
  NEXT_PAGE = 'span.next>a'


  # 解析页面
  def self.album(args)
    agent = Spidr::Agent.new
    page = agent.visit_page args['url']
    album_info = self.album_info page
    album_info['url'] = args['url']
    pic_info_array = []
    while page
      page.doc.css(PIC_SELECTOR).map do |img|
        begin
          pic_info = self.img_url img['href']
          pic_info_array << pic_info
        rescue => e
          puts 'www.douban.com/photos/album.rb 错误 -> ' + e.to_s
          puts e.backtrace
          next
        end
      end
      next_node = self.next_page_node page
      page = if next_node then agent.visit_page next_node['href'] else nil end
    end
    download args, album_info, pic_info_array
  end

  # 获取相册信息
  def self.album_info(page)
    share_node = page.doc.at(SHARE_SELETOR)
    number_time = page.doc.css(QUANTITY_TIME_SELECTOR)[1].content.strip!.split ' '
    author_title = page.doc.at(AUTHOR_TITLE_SELECTOR).content.strip!.split '-'
    {
      :author => author_title[0].slice(0..-4),
      :title => author_title[1],
      :desc => share_node["data-title"],
      :number => number_time[0],
      :time => number_time[2],
    }
  end

  # 获取图片的URL
  def self.img_url(url)
    agent = Spidr::Agent.new
    pic_page = agent.visit_page url
    url.chop! if url.end_with? '/'
    pid = Util.after_last_symbol(url)
    if pic_page.doc.at(SINGLE_LARGE_PIC_JUDGE_SELECTOR)
      # 图片为大图
      large_pic_url = "http://www.douban.com/photos/photo/#{pid}/large"
      pic_page = agent.visit_page large_pic_url
      img_node = pic_page.doc.at(SINGLE_LARGE_PIC_SELECTOR)
      {
        :desc => img_node['title'],
        :url => img_node['src'],
      }
    else 
      # 正常大小
      pic_div = pic_page.doc.at(SINGLE_PIC_DIV_SELECTOR)
      img_node = pic_div.at(SINGLE_PIC_SELECTOR)
      desc_node = pic_div.at(SINGLE_PIC_DESC_SELECTOR)
      {
        :desc => desc_node.content,
        :url => img_node['src'],
      }
    end
  end

  # 处理分页
  def self.next_page_node(page)
    sleep TIME_INTERVAL
    page.doc.at(NEXT_PAGE)
  end

  # 下载图片
  def self.download(args, album_info, pic_info_array)
    store_path = args["store_path"]
    info_path = store_path + '/' + album_info[:title] + ".txt"
    unless Dir.exist?(store_path)
      FileUtils.mkdir_p(store_path)
    end
    url_fail = []
    pic_info_array.each do |pic_info|
    end
    File.open info_path,'w' do |info|
      info.write "-------------------- #{ Time.now.strftime('%Y 年 %m 月 %d 日 %H 时 %M 分 %S 秒')} --------------------------\n"
      info.write "豆瓣ID：#{ album_info[:author] }\n"
      info.write "相册名称：#{ album_info[:title] }\n"
      info.write "相册描述：#{ album_info[:desc] }\n"
      info.write "图片数目：#{ album_info[:number] }\n"
      info.write "创建时间：#{ album_info[:time] }\n"
      pic_info_array.each_with_index do |pic_info,index|
        info.write "图片 #{index}：\n"
        info.write "描述：#{ pic_info[:desc] }\n"
        info.write "地址：#{ pic_info[:url] }\n"
        file_name = Util.after_last_symbol(pic_info[:url]) 
        result = Remember.image_download(store_path, file_name, pic_info[:url], TIME_INTERVAL)
        if result
          info.write "下载成功\n"
        else
          info.write "下载失败\n"
          url_fail << pic_info[:url]
        end
      end
      info.write "共#{pic_info_array.length}张图片"
      if url_fail.length > 0
        info.write "#{url_fail.length}张图片下载失败，详情见txt文件"
      end
      info.close
    end
  end
end
